const tool = require('../tools/tool')

module.exports = {
    async getList() {
        return await tool.dbf().selectWithParams(`select * from category`)
    },
    async getSingle(id) {
        return (await tool.dbf().selectWithParams(`select * from category where id = ?`, [id]))[0]
    },
    async delete(id) {
        let re = await tool.dbf().selectWithParams(`select count(*) as total from question where categoryId = ?`, [id])
        if (re[0].total) {
            throw '当前类别还有题目，不能删除'
        }
        await tool.dbf().deleteById('category', id)
    },
    async update(id, name) {
        await tool.dbf().updateById('category', id, {
            name
        })
    },
    async add(name) {
        let id = await tool.dbf().insertInto('category', {
            name
        })
        return id
    },
    async getAllCategoriesString() {
        let re = await this.getList()
        let str = ''
        for (let i = 0; i < re.length; i++) {
            str += `${re[i].id}：${re[i].name};`
        }
        return str
    }
}